package com.ruoyi.web.controller.house;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.balanceReturn.service.IHouseReturnTService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.cost.domain.FundCostT;
import com.ruoyi.cost.domain.HouseDoorCost;
import com.ruoyi.cost.service.IHouseCostTService;
import com.ruoyi.cost.service.IHouseDoorCostService;
import com.ruoyi.costQuery.domain.HouseCostT;
import com.ruoyi.costQuery.service.IHouseCostQueryTService;
import com.ruoyi.data.DataUtils;
import com.ruoyi.data.MD5;
import com.ruoyi.door.domain.HouseDoorT;
import com.ruoyi.door.service.IHouseDoorTService;
import com.ruoyi.info.domain.HouseDoorInfoT;
import com.ruoyi.info.service.IHouseDoorInfoTService;
import com.ruoyi.parameter.domain.HouseDoorParameterT;
import com.ruoyi.parameter.service.IHouseDoorParameterTService;
import com.ruoyi.project.domain.ParameterSingleVO;
import com.ruoyi.project.service.IHouseProjectTService;
import com.ruoyi.purpose.domain.HousePurposeT;
import com.ruoyi.purpose.service.IHousePurposeTService;
import com.ruoyi.refund.domain.HouseRefundT;
import com.ruoyi.refund.service.IHouseRefundTService;
import com.ruoyi.repairQuery.domain.RepairQueryT;
import com.ruoyi.repairQuery.service.IRepairQueryService;
import com.ruoyi.setup.domain.HouseSetupT;
import com.ruoyi.setup.service.IHouseSetupTService;
import com.ruoyi.util.SysParamKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * 户管理Controller
 * 
 * @author lijie
 * @date 2023-04-20
 */
@RestController
@RequestMapping("/house/door")
public class HouseDoorTController extends BaseController
{
    @Autowired
    private IHouseDoorTService houseDoorTService;

    @Autowired
    private IHousePurposeTService housePurposeTService;

    @Autowired
    private IHouseCostQueryTService houseCostQueryTService;

    @Autowired
    private IRepairQueryService repairQueryService;

    @Autowired
    private IHouseSetupTService houseSetupTService;

    @Autowired
    private IHouseDoorInfoTService houseDoorInfoTService;

    @Autowired
    private IHouseDoorCostService houseDoorCostService;

    @Autowired
    private IHouseDoorParameterTService houseDoorParameterTService;

    @Autowired
    private IHouseCostTService houseCostTService;

    @Autowired
    private IHouseProjectTService houseProjectTService;

    @Autowired
    private IHouseRefundTService houseRefundTService;

    @Autowired
    private IHouseReturnTService houseReturnTService;

    /**
     * 查询户管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HouseDoorT houseDoorT) throws Exception {
        startPage();
        if(houseDoorT.getUserName()!=null){
            houseDoorT.setUserName(MD5.encrypt(houseDoorT.getUserName()));
        }
        List<HouseDoorT> list = houseDoorTService.selectHouseDoorTList(houseDoorT);
        if (list.size()>0) {
            for (HouseDoorT houseDoorVO : list) {
                houseDoorVO.setPapersCode(MD5.decrypt(houseDoorVO.getPapersCode()));
                houseDoorVO.setUserName(MD5.decrypt(houseDoorVO.getUserName()));
                houseDoorVO.setTel(MD5.decrypt(houseDoorVO.getTel()));
            }
            if (getDataTableSumJudge(list)) {
                HouseDoorT houseVO = new HouseDoorT();
                houseVO = houseDoorTService.selectHouseDoorSum(houseDoorT);
                if (houseVO != null) {
                    houseVO.setAreaName("合计");
                }
                list.add(houseVO);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出户管理列表
     */
    @Log(title = "户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HouseDoorT houseDoorT) throws Exception {
        List<HouseDoorT> list = houseDoorTService.selectHouseDoorTList(houseDoorT);
        for(HouseDoorT houseDoorVO:list){
            houseDoorVO.setPapersCode(MD5.decrypt(houseDoorVO.getPapersCode()));
            houseDoorVO.setUserName(MD5.decrypt(houseDoorVO.getUserName()));
            houseDoorVO.setTel(MD5.decrypt(houseDoorVO.getTel()));
        }
        if(getDataTableSumJudge(list)){
            HouseDoorT houseVO = houseDoorTService.selectHouseDoorSum(houseDoorT);
            if(houseVO!=null){
                houseVO.setAreaName("合计");
            }
            list.add(houseVO);
        }
        ExcelUtil<HouseDoorT> util = new ExcelUtil<HouseDoorT>(HouseDoorT.class);
        util.exportExcel(response, list, "户管理数据");
    }

    /**
     * 获取户管理详细信息
     */
   @GetMapping(value = "/{doorId}")
    public AjaxResult getInfo(@PathVariable("doorId") Long doorId) throws Exception {
        HouseDoorT houseDoorT = houseDoorTService.selectHouseDoorTByDoorId(doorId);
        houseDoorT.setPapersCode(MD5.decrypt(houseDoorT.getPapersCode()));
        houseDoorT.setUserName(MD5.decrypt(houseDoorT.getUserName()));
        houseDoorT.setTel(MD5.decrypt(houseDoorT.getTel()));
        return AjaxResult.success(houseDoorT);
    }

    /**
     * 获取户管理详细信息
     */
    @GetMapping(value = "/getDoorAddr/{doorId}")
    public AjaxResult getDoorAddr(@PathVariable("doorId") Long doorId)
    {
        HouseDoorT houseDoorT = houseDoorTService.selectHouseDoorAddrByDoorId(doorId);
        return AjaxResult.success(houseDoorT);
    }
    /**
     * 新增户管理
     */
    @Log(title = "户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HouseDoorT houseDoorT) throws Exception {
        int id = houseDoorTService.getDoorId();
        HousePurposeT housePurposeT = new HousePurposeT();
        housePurposeT = housePurposeTService.selectHousePurposeTByPurposeName(houseDoorT.getPurposeName());
        String FeeStandards = getFeeStandards();
        if ("1".equals(FeeStandards)){
            Double budgetMoney = DataUtils.multiplyTwo(houseDoorT.getPrice(),houseDoorT.getSpace());
            houseDoorT.setBudgetMoney(budgetMoney);
        }else if("2".equals(FeeStandards)){
            Double budgetMoney = DataUtils.saveTwoTruncation(houseDoorT.getPrice()*houseDoorT.getSpace());
            houseDoorT.setBudgetMoney(budgetMoney);
        } else if("4".equals(FeeStandards)){
            Double budgetMoney = DataUtils.saveOneTruncation(houseDoorT.getPrice()*houseDoorT.getSpace());
            houseDoorT.setBudgetMoney(budgetMoney);
        } else if("3".equals(FeeStandards)){
            Double budgetMoney = DataUtils.multiplyOne(houseDoorT.getPrice(),houseDoorT.getSpace());
            houseDoorT.setBudgetMoney(budgetMoney);
        } else if ("5".equals(FeeStandards)){
            Double budgetMoney = DataUtils.doubleFloor(houseDoorT.getPrice()*houseDoorT.getSpace());
            houseDoorT.setBudgetMoney(budgetMoney);
        } else {
            Double budgetMoney = DataUtils.intFloor(houseDoorT.getPrice()*houseDoorT.getSpace());
            houseDoorT.setBudgetMoney(budgetMoney);
        }
        houseDoorT.setPurposeId(housePurposeT.getPurposeId());
        HouseDoorT vo=new HouseDoorT();
        vo.setAreaName(houseDoorT.getAreaName());
        vo.setDoorName(houseDoorT.getDoorName());
        vo.setGroupName(houseDoorT.getGroupName());
        vo.setUnitName(houseDoorT.getUnitName());
        vo=houseDoorTService.selectDoor(vo);
        if(vo!=null){
            return AjaxResult.error("该户信息已存在");
        }
        String houseId = (DateUtils.dateTimeNow()).substring(2,4) + String.format("%" + 6 + "d", id+1).replace(" ", "0");
        houseDoorT.setCreater(getUsername());
        houseDoorT.setHouseId(houseId);
        if(houseDoorT.getPapersCode()!=null){
            houseDoorT.setPapersCode(MD5.encrypt(houseDoorT.getPapersCode()));
        }
        if(houseDoorT.getUserName()!=null){
            houseDoorT.setUserName(MD5.encrypt(houseDoorT.getUserName()));
        }
        if(houseDoorT.getTel()!=null){
            houseDoorT.setTel(MD5.encrypt(houseDoorT.getTel()));
        }
        houseDoorT.setRateType("0");
        return toAjax(houseDoorTService.insertHouseDoorT(houseDoorT));
    }

    /**
     * 修改户管理
     */
    @Log(title = "户管理", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/update/{areaName}/{groupName}/{unitName}/{doorName}/{doorId}")
    public AjaxResult edit(@PathVariable("areaName") String areaName,
                           @PathVariable("groupName") String groupName,
                           @PathVariable("unitName") String unitName,
                           @PathVariable("doorName") String doorName,
                           @PathVariable("doorId") Long doorId) throws Exception {
        HouseDoorT doorVO = new HouseDoorT();
        doorVO.setAreaName(areaName);
        doorVO.setGroupName(groupName);
        doorVO.setUnitName(unitName);
        doorVO.setDoorName(doorName);
        doorVO.setDoorId(doorId);

        // 判断是否已有相同房屋信息
        HouseDoorT existingDoor = houseDoorTService.selectDoor(doorVO);
        if (existingDoor != null) {
            throw new RuntimeException("该房屋下已有其他房子，不允许修改");
        }

        // 获取目标房屋信息
        HouseDoorT targetDoor = houseDoorTService.selectHouseDoorTByDoorId(doorId);
        if (targetDoor == null) {
            throw new RuntimeException("未找到该户信息");
        }

        RepairQueryT houseRQueryVO = new RepairQueryT();
        houseRQueryVO.setHouseId(targetDoor.getHouseId());
        // 检查是否有维修记录
        List<RepairQueryT> repairList = repairQueryService.selectRepairQueryList(houseRQueryVO);
        if (repairList.size() > 0) {
            throw new RuntimeException("该房屋下已有维修记录，不允许修改");
        }

        return toAjax(houseDoorTService.updateHouseDoorT(doorVO));
    }

    /**
     * 删除户管理
     */
    @Log(title = "户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{doorIds}")
    public AjaxResult remove(@PathVariable Long[] doorIds)
    {
        for(Long doorId:doorIds){
            HouseDoorT houseDoorT = new HouseDoorT();
            houseDoorT = houseDoorTService.selectHouseDoorTByDoorId(doorId);
            HouseCostT houseCostT = new HouseCostT();
            houseCostT.setHouseId(houseDoorT.getHouseId());
            List<HouseCostT> costList = houseCostQueryTService.selectHouseCostTList(houseCostT);
            RepairQueryT repairQueryVO = new RepairQueryT();
            repairQueryVO.setHouseId(houseDoorT.getHouseId());
            List<RepairQueryT> list = repairQueryService.selectRepairQueryList(repairQueryVO);
            if(costList.size()>0||list.size()>0){
                return AjaxResult.error("操作失败,该用户已缴过费用或者已经产生维修！");
            }
        }
        return toAjax(houseDoorTService.deleteHouseDoorTByDoorIds(doorIds));
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport,String areaName) throws Exception
    {
        ExcelUtil<HouseDoorT> util = new ExcelUtil<HouseDoorT>(HouseDoorT.class);
        List<HouseDoorT> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = houseDoorTService.importUser(userList, updateSupport, operName,areaName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<HouseDoorT> util = new ExcelUtil<HouseDoorT>(HouseDoorT.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 查询计息列表
     */
    @GetMapping("/listRateQuery")
    public TableDataInfo listRateQuery(HouseDoorT houseDoorT)
    {
        startPage();
        List<HouseDoorT> list =new ArrayList<>();
        list = houseDoorTService.selectHouseRateTList(houseDoorT);
            if (list.size()>0) {
                if (getDataTableSumJudge(list)) {
                    HouseDoorT houseDoorVO = houseDoorTService.selectHouseRateTListSum(houseDoorT);
                    houseDoorVO.setHouseId("合计");
                    list.add(houseDoorVO);
                }
            }
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importAllData")
    public AjaxResult importAllData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<HouseDoorT> util = new ExcelUtil<HouseDoorT>(HouseDoorT.class);
        List<HouseDoorT> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = houseDoorTService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }


    /**
     * 首页信息
     */
    @GetMapping(value = "/getIndexSelectBoxCount01")
    public AjaxResult getIndexSelectBoxCount01 (){
        HouseDoorT vo =new HouseDoorT();
        HouseDoorT vo1 =new HouseDoorT();
        HouseDoorT vo2 =new HouseDoorT();
        HouseDoorT vo3 =new HouseDoorT();
        HouseDoorT vo4 =new HouseDoorT();
        vo1 = houseDoorTService.getBudgetInfo();
        vo2 = houseDoorTService.getCostInfo();
        vo3 = houseDoorTService.getUnpaidInfo();
        vo4 = houseDoorTService.getRepairInfo();
        vo.setBudgetMoney(vo1.getBudgetMoney());
        vo.setDoorSum(vo1.getDoorSum());
        vo.setCostMoney(vo2.getCostMoney());
        vo.setCostMoneySum(vo2.getCostMoneySum());
        vo.setUnpaidMoney(vo3.getUnpaidMoney());
        vo.setUnpaidSum(vo3.getUnpaidSum());
        vo.setRepairMoney(vo4.getRepairMoney());
        vo.setRepairSum(vo4.getRepairSum());
        return AjaxResult.success(vo);
    }

    public String getFeeStandards(){
        HouseSetupT list = houseSetupTService.selectHouseSetupTByFeeStandards();
        return list.getFeeStandards();
    }

    public static void main(String[] args) throws Exception {
        String a="1pFmrp6fWpE=";
        String b="uuV9t7nKnFaNyWKLGBHZEA==";

        String c=MD5.decrypt(a);
        String d=MD5.decrypt(b);

        System.out.println(c);
        System.out.println(d);

    }


    /**
     * 修改户信息修改
     */
    @Log(title = "户信息修改", businessType = BusinessType.UPDATE)
    @PutMapping(value="updateInfo")
    public AjaxResult updateInfo(@RequestBody HouseDoorInfoT houseDoorInfoT ) throws Exception {
        if(houseDoorInfoT.getPapersCode()!=null){
            houseDoorInfoT.setPapersCode(MD5.encrypt(houseDoorInfoT.getPapersCode()));
        }
        if(houseDoorInfoT.getUserName()!=null){
            houseDoorInfoT.setUserName(MD5.encrypt(houseDoorInfoT.getUserName()));
        }
        if(houseDoorInfoT.getTel()!=null){
            houseDoorInfoT.setTel(MD5.encrypt(houseDoorInfoT.getTel()));
        }
        houseDoorInfoT.setCreater(getUsername());
        return toAjax(houseDoorInfoTService.updateHouseDoorInfoT(houseDoorInfoT));
    }

    //户资金修改
    @GetMapping(value = "/getDoorCostList/{houseId}")
    public TableDataInfo getDoorCostList(@PathVariable("houseId") String houseId) throws Exception {
        HouseDoorT houseDoorT = new HouseDoorT();
        houseDoorT.setHouseId(houseId);
        List<HouseDoorT> list = houseDoorCostService.selectHouseCostTList(houseDoorT);
        if(list.size()!=0) {
            for (HouseDoorT houseDoorVO : list) {
                houseDoorVO.setUserName(MD5.decrypt(houseDoorVO.getUserName()));
            }
        }
        return getDataTable(list);
    }


    @Log(title = "缴费信息修改")
    @GetMapping(value="/getDoorCost/{costId}")
    public AjaxResult edit(@PathVariable("costId") Long costId)
    {
        return AjaxResult.success(houseCostQueryTService.selectHouseCostTByCostId(costId));
    }

    @Log(title = "缴费信息修改", businessType = BusinessType.INSERT)
    @PutMapping(value="/updateDoorCost")
    public AjaxResult updateDoorCost(@RequestBody HouseDoorT houseDoorT) throws Exception {
        HouseDoorT doorTempVO = new HouseDoorT();
        HouseDoorCost houseDoorCostT = new HouseDoorCost();
        doorTempVO = houseDoorCostService.selectHouseDoorCostTByCostId(houseDoorT);
        if(DataUtils.subMoney(doorTempVO.getCostMoney(),houseDoorT.getCostMoney()).compareTo(doorTempVO.getBalance())>=0d){
            throw new Exception("余额不足不允许修改！");
        }
        houseDoorCostT.setCostMoneyPre(doorTempVO.getCostMoney());
        houseDoorCostT.setCostDatePre(doorTempVO.getCostDate());
        houseDoorCostT.setBalancePre(doorTempVO.getBalance());
        houseDoorCostT.setCreater(houseDoorT.getCreater());
        houseDoorCostT.setBillNo(houseDoorT.getBillNo());
        houseDoorCostT.setBillNoPre(doorTempVO.getBillNo());
        houseDoorCostT.setRemark(houseDoorT.getRemark());
        houseDoorCostT.setHouseId(houseDoorT.getHouseId());
        houseDoorCostService.updateHouseCostT(houseDoorT);
        HouseDoorT houseDoorVO=houseDoorCostService.selectCostMoneySum(houseDoorT);
        if(houseDoorVO==null){
            houseDoorVO = new HouseDoorT();
            houseDoorVO.setCostMoney(0d);
        }
        HouseDoorT houseDoorVO3=houseDoorCostService.selectRepairPayMoneySum(houseDoorT);
        if(houseDoorVO3==null){
            houseDoorVO3 = new HouseDoorT();
            houseDoorVO3.setPayMoney(0d);
        }
        HouseDoorT houseDoorVO4=houseDoorCostService.selectRateMoneySum(houseDoorT);
        if(houseDoorVO4==null){
            houseDoorVO4 = new HouseDoorT();
            houseDoorVO4.setRateMoney(0d);
        }
        houseDoorT.setBalanceSum(DataUtils.subMoney(DataUtils.sumMoney(houseDoorVO.getCostMoney(),houseDoorVO4.getRateMoney()),houseDoorVO3.getPayMoney()));
        houseDoorT.setBalance(DataUtils.subMoney(houseDoorVO.getCostMoney(),houseDoorVO3.getPayMoney()));
        houseDoorT.setCostMoneySum(String.valueOf(houseDoorVO.getCostMoney()));
        houseDoorT.setCostDate(houseDoorT.getCostDate());
        houseDoorT.setEndDate(houseDoorVO.getCostDate());
        houseDoorT.setBillNo(houseDoorT.getBillNo());
        houseDoorT.setBillNoPre(doorTempVO.getBillNo());
        houseDoorT.setCostMoneyPre(doorTempVO.getCostMoney());
        houseDoorT.setCostDatePre(doorTempVO.getCostDate());
        houseDoorT.setBalancePre(doorTempVO.getBalance());
        houseDoorT.setCreater(getUsername());
        houseDoorT.setRemark(houseDoorT.getRemark());
        return toAjax(houseDoorCostService.updateHouseDoorT(houseDoorT));
    }


    // 查询户参数
    @GetMapping(value = "/getParameter/{doorId}")
    public AjaxResult getParameter(@PathVariable("doorId") Long doorId)
    {
        return AjaxResult.success(houseDoorParameterTService.selectHouseDoorParameterTByDoorId(doorId));
    }


    @Log(title = "户参数修改", businessType = BusinessType.UPDATE)
    @PutMapping(value="/updateParameter")
    public AjaxResult updateParameter(@RequestBody HouseDoorParameterT houseDoorParameterT) {

        HousePurposeT housePurposeT = new HousePurposeT();
        housePurposeT = housePurposeTService.selectHousePurposeTByPurposeId(houseDoorParameterT.getPurposeId());
        String FeeStandards = getFeeStandards();
        houseDoorParameterT.setCreater(getUsername());
        if (houseDoorParameterT.getPrice() != 0) {
            if ("1".equals(FeeStandards)) {
                Double budgetMoney = DataUtils.multiplyTwo(houseDoorParameterT.getPrice(), houseDoorParameterT.getSpace());
                houseDoorParameterT.setBudgetMoney(budgetMoney);
            } else if ("2".equals(FeeStandards)) {
                Double budgetMoney = DataUtils.saveTwoTruncation(houseDoorParameterT.getPrice() * houseDoorParameterT.getSpace());
                houseDoorParameterT.setBudgetMoney(budgetMoney);
            } else if ("4".equals(FeeStandards)) {
                Double budgetMoney = DataUtils.saveOneTruncation(houseDoorParameterT.getPrice() * houseDoorParameterT.getSpace());
                houseDoorParameterT.setBudgetMoney(budgetMoney);
            } else if ("3".equals(FeeStandards)) {
                Double budgetMoney = DataUtils.multiplyOne(houseDoorParameterT.getPrice(), houseDoorParameterT.getSpace());
                houseDoorParameterT.setBudgetMoney(budgetMoney);
            } else if ("5".equals(FeeStandards)) {
                Double budgetMoney = DataUtils.doubleFloor(houseDoorParameterT.getPrice() * houseDoorParameterT.getSpace());
                houseDoorParameterT.setBudgetMoney(budgetMoney);
            } else {
                Double budgetMoney = DataUtils.intFloor(houseDoorParameterT.getPrice() * houseDoorParameterT.getSpace());
                houseDoorParameterT.setBudgetMoney(budgetMoney);
            }
        }
        return toAjax(houseDoorParameterTService.updateHouseDoorParameterT(houseDoorParameterT));

    }


    //缴费
    @GetMapping(value = "/getCost/{doorId}")
    public AjaxResult getCost(@PathVariable("doorId") Long doorId) throws Exception {
        FundCostT fundCostVO = houseCostTService.selectFundCostTByDoorId(doorId);
        fundCostVO.setPapersCode(MD5.decrypt(fundCostVO.getPapersCode()));
        fundCostVO.setUserName(MD5.decrypt(fundCostVO.getUserName()));
        fundCostVO.setTel(MD5.decrypt(fundCostVO.getTel()));
        return AjaxResult.success(fundCostVO);
    }

    @Log(title = "缴费管理", businessType = BusinessType.UPDATE)
    @PutMapping(value="/insertCost")
    public AjaxResult insertCost(@RequestBody FundCostT fundCostT) throws Exception {
        fundCostT.setCreater(getUsername());
        if(fundCostT.getPapersCode()!=null){
            fundCostT.setPapersCode(MD5.encrypt(fundCostT.getPapersCode()));
        }
        if(fundCostT.getUserName()!=null){
            fundCostT.setUserName(MD5.encrypt(fundCostT.getUserName()));
        }
        if(fundCostT.getTel()!=null){
            fundCostT.setTel(MD5.encrypt(fundCostT.getTel()));
        }
        int costId = houseCostTService.updateFundCostT(fundCostT);
        HouseCostT houseCostVO = new HouseCostT();
        houseCostVO.setCostId(Long.valueOf(costId));
        return AjaxResult.success(houseCostVO);
    }

    @PutMapping("/weChatPay")
    @Transactional
    public AjaxResult weChatPay(@RequestBody FundCostT fundCostT) throws Exception {
        HouseCostT orderVO = new HouseCostT();
        orderVO.setOrderId(DateUtils.dateTimeNow() + fundCostT.getHouseId());
        orderVO.setUserName(MD5.encrypt(fundCostT.getUserName()));
        orderVO.setTel(MD5.encrypt(fundCostT.getTel()));
        orderVO.setPapersCode(MD5.encrypt(fundCostT.getPapersCode()));
        orderVO.setOrderMoney(fundCostT.getBudgetMoney());
        orderVO.setHouseId(fundCostT.getHouseId());
        orderVO.setOrderSts("0");
        HouseCostT vo = new HouseCostT();
        houseCostQueryTService.insertOrderInfo(orderVO);
        vo = houseCostQueryTService.selectOrderId(orderVO.getOrderId());
        String order_id = vo.getOrderId();
        int fee = (int) (vo.getOrderMoney() * 100);
        Double fee_display = vo.getOrderMoney();
        String business_id = vo.getHouseId();
        String body = "地址:" + fundCostT.getAreaName() +
                fundCostT.getGroupName() + fundCostT.getUnitName() + fundCostT.getDoorName() + "室" + vo.getOrderId() + "订单号";
        try {
            String pythonUrl = RuoYiConfig.getGetpythonAccount();
            /* String pythonUrl = "http://17.17.17.18:9527/back_service/do_unifiedorder_pay";*/
            URL url = new URL(pythonUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            String formdata =
                    "fee=" + URLEncoder.encode(String.valueOf(fee), "UTF-8") +
                            "&fee_display=" + URLEncoder.encode(String.valueOf(fee_display), "UTF-8") +
                            "&business_id=" + URLEncoder.encode(business_id, "UTF-8") +
                            "&body=" + URLEncoder.encode(body, "UTF-8") +
                            "&order_id=" + URLEncoder.encode(order_id, "UTF-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStream out = conn.getOutputStream();
            out.write(formdata.getBytes());
            out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            String jsonString = response.toString();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> jsonMap = objectMapper.readValue(jsonString, Map.class);
            boolean success = (boolean) jsonMap.get("success");
            String orderid = (String) jsonMap.get("order_id");
            if (success == true) {
                String path = RuoYiConfig.getGetipAccount();
                Map<String, String> map1 = new HashMap<String, String>();
                map1.put("addr", path + "weixin_" + orderid + ".png");
                return AjaxResult.success(map1);
            }
            System.out.println("python服务器的响应： " + response);
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(1);
    }


    //退款
    @GetMapping(value = "/getRefundList/{houseId}")
    public TableDataInfo getRefundList(@PathVariable("houseId") String houseId) throws Exception {
        HouseRefundT houseRefundT = new HouseRefundT();
        houseRefundT.setHouseId(houseId);
        List<HouseRefundT> list = houseRefundTService.selectHouseRefundTList(houseRefundT);
        for(HouseRefundT houseRefundVO:list){
            houseRefundVO.setUserName(MD5.decrypt(houseRefundVO.getUserName()));
        }
        return getDataTable(list);
    }


    @Log(title = "缴费信息修改")
    @GetMapping(value="/getRefund/{costId}")
    public AjaxResult getRefund(@PathVariable("costId") Long costId)
    {
        HouseRefundT houseRefundVO = houseRefundTService.selectHouseRefundNote(costId);
        return AjaxResult.success(houseRefundVO);
    }

    @Log(title = "缴费信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/updateRefund/{costId}/{refundDate}")
    public AjaxResult remove(@PathVariable Long costId,@PathVariable("refundDate") Date refundDate)
    {
        int costid2 = houseRefundTService.deleteHouseRefundTByCostIds(costId,getUsername(),refundDate);
        if(costid2==2){
            return AjaxResult.error("所剩余额不足不允许退款！");
        }
        HouseCostT houseCostVO = new HouseCostT();
        houseCostVO.setCostId(Long.valueOf(costid2));
        return AjaxResult.success(houseCostVO);

    }

    //资金返还
    @Log(title = "资金返还", businessType = BusinessType.DELETE)
    @DeleteMapping("/delReturn/{doorId}")
    public AjaxResult delReturn(@PathVariable Long doorId)
    {
        int costid2= houseReturnTService.insertHouseReturnTByDoorIds(doorId,getUsername());
        HouseCostT houseCostVO = new HouseCostT();
        houseCostVO.setCostId(Long.valueOf(costid2));
        return AjaxResult.success(houseCostVO);

    }


    /**
     * 获取户
     */
    @GetMapping(value = "/getDoorInfo/{areaName}/{groupName}/{unitName}")
    public TableDataInfo getDoorInfo(@PathVariable("areaName") String areaName, @PathVariable("groupName") String groupName, @PathVariable("unitName") String unitName) {
        HouseDoorT houseDoorT = new HouseDoorT();
        houseDoorT.setAreaName(areaName);
        houseDoorT.setGroupName(groupName);
        houseDoorT.setUnitName(unitName);
        List<HouseDoorT> list = houseDoorTService.selectHouseDoorTList1(houseDoorT);
        return getDataTable(list);
    }

}
